#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QScrollBar>
#include <QStyle>
#include <QTimer>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("应急演练系统自动更新程序");
    ui->menuBar->hide();

    this->setWindowFlags(Qt::FramelessWindowHint); // 去掉边框和标题栏
    ui->plainTextEdit->verticalScrollBar()->style()
            ->polish(ui->plainTextEdit->verticalScrollBar());   // 刷新滚动条样式


//    config.beginGroup("main");
//    initIni("toPath","D:/EdsPC");
//    initIni("serverAddress","http://soft.pwidc.cn:8016/PC_ClientVersions/PC_Release");
//    initIni("binAddress","http://soft.pwidc.cn:8016/PC_ClientVersions/Versions.bin");
//    initIni("exeFileName","EdsPC.exe");


//    config.setValue("toPath",QDir::currentPath());


    connect(&resFileMgr,&ResFileMgr::sigBinDownload,[=](){
        resFileMgr.loadFile("Versions.bin");
        QTimer::singleShot(1000,[=](){on_actiondownTest_triggered();});
    });

    resFileMgr.downloadBin();

    auto updateProgress = new QTimer;
    updateProgress->callOnTimeout([=](){
        ui->progressBar->setPercentage(ui->progressBar->getPercentage()+0.01);
    });
    updateProgress->start(1000);

    LOG.setCallbackFunc([=](QString info){
//        if(info.contains('-')){
//            return;
//        }

        ui->plainTextEdit->appendPlainText(info);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}





void MainWindow::on_actiondownTest_triggered()
{
    qDebug()<<__FUNCTION__;

    if(resFileMgr.getResList().isEmpty()){
        LOG<<"加载文件列表失败";
        return;
    }

//    QString serverAddress = config.value("serverAddress").toString();
//    QString toPath = config.value("toPath").toString();
    QString serverAddress = "http://soft.pwidc.cn:8016/PC_ClientVersions/PC_Release";
    QString toPath = QDir::currentPath();


    connect(&downMgr,&DownloadToolMgr::sigCurSpeed,
            [=](double bps,qint64 bytesReadCount,qint64 totalBytesCount){
        qDebug()<<bps<<bytesReadCount<<totalBytesCount;

        QString speed = formatSpeedBps(bps);
        ui->curSpeedLabel->setText(speed);

        QString progressText = formatReadCountBps(bytesReadCount,totalBytesCount);
        ui->progressLabel->setText(progressText);

        double progress = (double)bytesReadCount/totalBytesCount;
        ui->progressBar->setPercentage(progress);

    });

    connect(&downMgr,&DownloadToolMgr::sigtTaskProgress,[this](int done , int count){
        qDebug()<< done  << count;
        QString info = "下载文件数量 %1/%2";
        info = info.arg(done).arg(count);
        ui->progressCountLabel->setText(info);
    });

    connect(&downMgr,&DownloadToolMgr::sigDownDownFinished,[this](){
        Done();
    });

    connect(&downMgr,&DownloadToolMgr::sigCurDownLoadFile,[=](QString fileUrl,bool isDeno){
        QString info;
        if(isDeno){
            info += "- 已完成   ";
        }else{
            info += "- 正在下载 ";
        }
        info += fileUrl.mid(serverAddress.count()+1);

        LOG<<info;
    });




    ResFileMgr dirMgr;
    dirMgr.loadFormLocalDir(toPath);

    ResFileMgr toDown;

    for(auto item : resFileMgr.getResList()){
        if(dirMgr.getResList().contains(item.Name)){
            auto fileMd5 = dirMgr.getResList().value(item.Name).Md5;
            if(fileMd5 == item.Md5){
                continue;
            }
        }

        toDown.append(item);

        QString url = serverAddress+"/"+item.Name;
        QString localFilePath = toPath+"/"+item.Name;
        MyDirTools dir;
        dir.createDirectoryRecursively(localFilePath,true);

        auto task = new DownloadTool(url,localFilePath);
        downMgr.addTask(task);
    }
    if(resFileMgr.getResList().count() > 0 && downMgr.count()==0){
        ui->progressBar->setPercentage(1);
        Done();
    }else{
        downMgr.setTotalBytesCount(toDown.getTotalBytesCount());
        downMgr.start();
    }
}


void MainWindow::on_actiontest1_triggered()
{
    on_actiondownTest_triggered();
}

QString MainWindow::formatSpeedBps(qint64 bps) {
    qint64 bytesPerSecond = bps / 8;
    QString unit;
    double speed;

    if (bytesPerSecond < 1024) {
        speed = bytesPerSecond;
        unit = "B/S";
    } else if (bytesPerSecond < 1024 * 1024) {
        speed = bytesPerSecond / 1024.0;
        unit = "K/S";
    } else if (bytesPerSecond < 1024 * 1024 * 1024) {
        speed = bytesPerSecond / (1024.0 * 1024.0);
        unit = "M/S";
    } else {
        speed = bytesPerSecond / (1024.0 * 1024.0 * 1024.0);
        unit = "G/S";
    }

    return QString("%1 %2").arg(QString::number(speed, 'f', 2)).arg(unit);
}

QString MainWindow::formatReadCountBps(qint64 bytesReadCount, qint64 totalBytesCount)
{
    qint64 bytesPerSecond = totalBytesCount / 8;
    QString unit;
    double zoom;

    if (bytesPerSecond < 1024) {
        unit = "B";
        zoom = 1;
    } else if (bytesPerSecond < 1024 * 1024) {
        zoom = 1024.0;
        unit = "K";
    } else if (bytesPerSecond < 1024 * 1024 * 1024) {
        zoom =  (1024.0 * 1024.0);
        unit = "M";
    } else {
        zoom =  (1024.0 * 1024.0 * 1024.0);
        unit = "G";
    }

    qint64 read = bytesReadCount/zoom;
    qint64 total = totalBytesCount/zoom;

    QString info = "%1 %2 / %3 %4";
    info = info.arg(read).arg(unit).arg(total).arg(unit);
    return info;

}


#include <windows.h>
void MainWindow::Done()
{
    static bool isDone = false;
    if(isDone){
        return;
    }
    isDone = true;


    qDebug()<<__FUNCTION__;
    QString info = "更新已完成，即将启动客户端，请稍等......";
    ui->label->setText(info);


    QString toPath = QDir::currentPath();
    auto exeName = "EdsPC.exe";
    auto exeFileName = toPath+"/"+exeName;

    auto cmd = QString("start /d \"%0\" \"%1\" ");
//    auto cmd = QString("cd %0  start %1 ");

    cmd = cmd.arg(toPath).arg(exeFileName);


//    LOG << cmd;

    return;

    QTimer::singleShot(2000,[=](){
        LOG<<"正在启动...";
        WinExec(exeFileName.toLocal8Bit().data(),SW_SHOW);
        QTimer::singleShot(3000,[=](){
            QApplication::quit();
        });
    });

    return;
}

void MainWindow::initIni(QString key, QString value)
{
//    if(config.value(key).toString().isEmpty()){
//        config.setValue(key,value);
//    }
}

#include <qt_windows.h>
void MainWindow::on_actionexe_triggered()
{


//    WinExec(exeFileName.toLocal8Bit().data(),SW_HIDE);
}


void MainWindow::on_actiondirTest_triggered()
{
    MyDirTools d;
    d.test();
}


void MainWindow::on_actionloadDir_triggered()
{
    QString toPath = QDir::currentPath();
    ResFileMgr dirMgr;

    dirMgr.loadFormLocalDir(toPath);
}

